package org.zt.java.dal.context;

import java.util.Stack;

import org.springframework.core.NamedThreadLocal;
import org.zt.java.dal.config.vo.MethodInfo;


public class ContextHolder {

	private static ThreadLocal<Boolean> globalTransactional = new NamedThreadLocal<Boolean>("线程栈全局事务标识");
	private static ThreadLocal<Stack<MethodInfo>> methodStack = new NamedThreadLocal<Stack<MethodInfo>>("调用的方法栈信息") {
		@Override
		protected Stack<MethodInfo> initialValue() {
			return new Stack<MethodInfo>();
		}
	};

	public static void pushMethodInfo(MethodInfo methodInfo) {
		if (Boolean.TRUE.equals(methodInfo.getTx())) {
			setGlobalTransactional(true);
		}

		methodStack.get().push(methodInfo);
	}

	public static void popMethodInfo() {
		if (isStackEmpty()) {//避免堆栈空时，pop报错
			return;
		}
		methodStack.get().pop();
	}

	public static boolean isStackEmpty() {
		return methodStack.get().isEmpty();
	}

	public static MethodInfo getCurrentMethodInfo() {
		if (isStackEmpty()) {//避免堆栈空时，peek报错
			return null;
		}
		return methodStack.get().peek();
	}

	public static MethodInfo getFirstMethodInfo() {
		if (isStackEmpty()) {
			return null;
		}
		return methodStack.get().get(0);
	}

	private static void setGlobalTransactional(boolean begin) {
		// 如果之前已经开启了事务，则直接返回
		if (Boolean.TRUE.equals(globalTransactional.get())) {
			return;
		}

		globalTransactional.set(begin ? Boolean.TRUE : null);
	}

	public static Boolean isGlobalTransactional() {
		return globalTransactional.get() != null ? globalTransactional.get() : false;
	}

	public static void clearAll() {
		globalTransactional.remove();
		methodStack.remove();
	}

}
